<script lang="ts" setup>
import { i18n } from "@/locales";
import type { NodeViewProps } from "@/tiptap/vue-3";
import { NodeViewWrapper } from "@/tiptap/vue-3";
import { computed, ref } from "vue";
import Audio from "./index";

const props = defineProps<NodeViewProps>();

const src = computed({
  get: () => {
    return props.node?.attrs.src;
  },
  set: (src: string) => {
    props.updateAttributes({ src: src });
  },
});

const autoplay = computed(() => {
  return props.node.attrs.autoplay;
});

const loop = computed(() => {
  return props.node.attrs.loop;
});

function handleSetFocus() {
  props.editor.commands.setNodeSelection(props.getPos() || 0);
}

const showLinkInput = ref(false);
const linkInputRef = ref();
const fileInputRef = ref();

const handleUploadClick = () => {
  fileInputRef.value?.click();
};

const handleLinkClick = () => {
  showLinkInput.value = true;
  setTimeout(() => {
    linkInputRef.value?.focus();
  }, 100);
};

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  // 获取上传处理器
  const uploadHandler = props.editor.extensionManager.extensions.find(
    ext => ext.name === Audio.name
  )?.options?.uploadHandler;

  if (uploadHandler && typeof uploadHandler === 'function') {
    try {
      const uploadedUrl = await uploadHandler(file);
      if (uploadedUrl) {
        src.value = uploadedUrl;
      }
    } catch (error) {
      console.error('上传音频失败:', error);
    }
  } else {
    // 如果没有上传处理器，使用本地 URL
    const localUrl = URL.createObjectURL(file);
    src.value = localUrl;
  }

  // 重置文件输入
  target.value = '';
};

const handleLinkSubmit = () => {
  showLinkInput.value = false;
};
</script>

<template>
  <node-view-wrapper as="div" class="audio-wrapper">
    <div class="audio-container">
      <div v-if="!src" class="audio-upload-wrapper">
        <div v-if="!showLinkInput" class="upload-placeholder">
          <div class="upload-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 3v9.28c-.47-.17-.97-.28-1.5-.28C8.01 12 6 14.01 6 16.5S8.01 21 10.5 21c2.31 0 4.2-1.75 4.45-4H15V6h4V3h-7z"/>
            </svg>
          </div>
          <div class="upload-actions">
            <button class="upload-btn" @click="handleUploadClick">
              {{ i18n.global.t('editor.common.button.upload') || '上传' }}
            </button>
            <button class="link-btn" @click="handleLinkClick">
              {{ i18n.global.t('editor.common.button.input_link') || '输入链接' }}
            </button>
          </div>
          <input
            ref="fileInputRef"
            type="file"
            accept="audio/*"
            style="display: none"
            @change="handleFileChange"
          />
        </div>
        <div v-else class="link-input-wrapper">
          <input
            ref="linkInputRef"
            v-model.lazy="src"
            class="link-input"
            :placeholder="i18n.global.t('editor.common.placeholder.link_input') || '请输入音频链接'"
            @blur="handleLinkSubmit"
            @keyup.enter="handleLinkSubmit"
            @focus="handleSetFocus"
          />
        </div>
      </div>
      <audio
        v-else
        controls
        :autoplay="autoplay"
        :loop="loop"
        :src="node!.attrs.src"
        @mouseenter="handleSetFocus"
      ></audio>
    </div>
  </node-view-wrapper>
</template>

<style lang="scss" scoped>
.audio-wrapper {
  display: inline-block;
  width: 100%;
}

.audio-container {
  position: relative;
  display: inline-block;
  height: 100%;
  width: 100%;
  overflow: hidden;
  text-align: center;
  transition: all 0.2s;
}

.audio-upload-wrapper {
  padding: 2rem;
  min-height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1.5rem;
}

.upload-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: color-mix(in srgb, var(--editor-primary-color, #9373ee) 10%, transparent);
  display: flex;
  align-items: center;
  justify-content: center;
  
  svg {
    color: var(--editor-primary-color, #9373ee);
  }
}

.upload-actions {
  display: flex;
  gap: 0.75rem;
}

.upload-btn,
.link-btn {
  padding: 0.5rem 1.5rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid var(--editor-input-border);
  background: var(--editor-input-bg);
  color: var(--editor-input-text);
}

.upload-btn:hover,
.link-btn:hover {
  border-color: var(--editor-primary-color);
  color: var(--editor-primary-color);
}

.link-input-wrapper {
  width: 100%;
  padding: 0.375rem;
}

.link-input {
  display: block;
  width: 100%;
  border-radius: 0.375rem;
  border: 1px solid var(--editor-input-border);
  background-color: var(--editor-input-bg);
  padding: 0.5rem 0.75rem;
  font-size: 0.875rem;
  color: var(--editor-input-text);

  &:focus {
    border-color: var(--editor-input-focus-border);
    outline: none;
    box-shadow: 0 0 0 1px var(--editor-input-focus-border);
  }
}
</style>
